﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace AutoUpdateTool.Utils
{
    public class NginxHelper
    {
        public string nginxPath { get; set; } = System.AppDomain.CurrentDomain.BaseDirectory + "nginx-1.25.1";
        public NginxHelper(string path = "")
        {
            if (!string.IsNullOrEmpty(path))
            {
                nginxPath = path;
            }
        }
        /// <summary>
        /// 命令执行
        /// </summary>
        /// <param name="Arguments"></param>
        /// <param name="FileName"></param>
        /// <param name="CreateNoWindow"></param>
        /// <param name="UseShellExecute"></param>
        public void Cmd(string Arguments, string FileName = "nginx.exe", bool? CreateNoWindow = true, bool? UseShellExecute = true)
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo()
                {
                    CreateNoWindow = (bool)CreateNoWindow,
                    UseShellExecute = (bool)UseShellExecute,
                    WorkingDirectory = nginxPath,
                    FileName = FileName,
                    Arguments = Arguments
                };
                Process process = new Process();
                process.StartInfo = startInfo;
                process.OutputDataReceived += NginxProcess_OutputDataReceived;
                process.ErrorDataReceived += NginxProcess_ErrorDataReceived;

                process.Start();//执行  
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();//等待程序执行完退出进程  
                process.Close();//结束  
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void NginxProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            // 处理Nginx进程的输出信息
            // 例如，您可以将输出信息显示在WinForms应用程序的日志文本框中
            // textBoxLog.AppendText(e.Data + Environment.NewLine);
        }

        private void NginxProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            // 处理Nginx进程的错误信息
            // 例如，您可以将错误信息显示在WinForms应用程序的错误提示框中
            // MessageBox.Show(e.Data);
        }
        /// <summary>
        /// 服务检查
        /// </summary>
        /// <returns></returns>
        public bool CheckNginx()
        {
            try
            {
                string pidPath = nginxPath + "\\logs\\nginx.pid";
                if (File.Exists(pidPath))
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
            }
            return false;
        }
    }
}
